package com.yaowk.platform.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.json.FastJson;
import com.jfinal.kit.JMap;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.activerecord.tx.TxConfig;
import com.yaowk.authc.Kit.PasswordKit;
import com.yaowk.authc.model.User;
import com.yaowk.authc.model.UserRole;
import com.yaowk.common.kit.Constant;
import com.yaowk.common.kit.DateKit;
import com.yaowk.common.kit.I18nKit;
import com.yaowk.common.kit.ResultKit;
import com.yaowk.common.validator.RequiredIdValidator;
import com.yaowk.platform.model.*;
import com.yaowk.platform.model.page.CompanyPage;
import com.yaowk.platform.model.param.OtherParam;
import com.yaowk.platform.model.param.QualificationParam;
import com.yaowk.platform.model.param.TradeParam;
import com.yaowk.system.model.Platform;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import java.util.Date;
import java.util.List;

/**
 * 企业审核
 *
 * @authc yaowk
 * 2017/5/2
 */
@TxConfig(Constant.PLATFORM_MODULE)
public class CompanyController extends Controller {

    /**
     * 企业列表
     *
     * @param platformId|平台id|Integer|必填
     * @param pageSize|每页条数|Integer|否
     * @param pageNumber|当前页|Integer|否
     * @param tradeId|行业id|Integer|否
     * @param qualificationId|资质id|Integer|否
     * @param status|状态1-待审核2-已审核|Integer|否
     * @param name|企业名称|Integer|否
     * @title 企业列表
     */
    @RequiresPermissions("platform:read")
    public void list() {
        CompanyPage companyPage = getBean(CompanyPage.class, "");
        Page<Company> page = Company.dao.paginate(companyPage);
        renderJson(ResultKit.success(page));
    }

    /**
     * 查看审核信息
     *
     * @param id|企业id|Integer|必填
     * @title 查看审核信息
     */
    @RequiresPermissions("platform:read")
    @Before(RequiredIdValidator.class)
    public void info() {
        Integer id = getParaToInt("id");
        List<CompanyInfo> companyInfoList = CompanyInfo.dao.findByCompanyId(id);
        List<CompanyQualification> qualificationList = CompanyQualification.dao.findByCompanyId(id);
        List<CompanyTrade> tradeList = CompanyTrade.dao.findByCompanyId(id);
        Company company = Company.dao.findById(id);
        JMap result = JMap.create().set("company", company)
                .set("trades", tradeList)
                .set("qualifications", qualificationList)
                .set("others", companyInfoList);
        renderJson(ResultKit.success(result));
    }

    /**
     * 添加企业信息
     *
     * @title 添加企业信息
     */
    @RequiresPermissions("platform:update")
    @Before(Tx.class)
    public void add() {
        Integer platformId = getParaToInt("platformId");
        String userCode = getPara("userCode");
        String password = getPara("password");
        String rePassword = getPara("rePassword");
        String name = getPara("name");
        String trade = getPara("trade");
        String qualification = getPara("qualification");
        String others = getPara("others");

        if (!password.equals(rePassword)) {
            renderJson(ResultKit.fail(I18nKit.get("password_different", Constant.COMMON_MODULE, this)));
            return;
        }

        Date now = new Date();
        Platform platform = Platform.dao.findById(platformId);

        User user = new User();
        user.use(Constant.PLATFORM_MODULE);
        user.setUserCode(userCode)
                .setPassword(PasswordKit.passwordService.encryptPassword(password))
                .setUsername(platform.getSign() + userCode)
                .setCreateTime(now)
                .setPlatformId(platformId)
                .setStatus(0)
                .setType(1)
                .setName(name)
                .save();

        UserRole userRole = new UserRole();
        userRole.use(Constant.PLATFORM_MODULE).setUserId(user.getId()).setRoleId(3).save();

        FastJson fastJson = FastJson.getJson();
        TradeParam[] tradeParams = fastJson.parse(trade, TradeParam[].class);
        QualificationParam[] qualificationParams = fastJson.parse(qualification, QualificationParam[].class);
        OtherParam[] otherParams = fastJson.parse(others, OtherParam[].class);

        Company company = new Company();
        company.setUserId(user.getId())
                .setCreateTime(now)
                .setPlatformId(user.getPlatformId())
                .setName(name)
                .save();
        Integer companyId = company.getId();

        // 保存行业
        if (tradeParams != null)
            for (TradeParam tradeParam : tradeParams) {
                for (String file : tradeParam.getFiles()) {
                    CompanyTrade companyTrade = new CompanyTrade();
                    companyTrade.setCompanyId(companyId)
                            .setTradeId(tradeParam.getId())
                            .setAccessory(file)
                            .save();
                }
            }

        // 保存资质
        if (qualificationParams != null)
            for (QualificationParam qualificationParam : qualificationParams) {
                for (String file : qualificationParam.getFiles()) {
                    CompanyQualification companyQualification = new CompanyQualification();
                    companyQualification.setCompanyId(companyId)
                            .setQualificationId(qualificationParam.getId())
                            .setAccessory(file)
                            .setBeginTime(DateKit.toDate(qualificationParam.getBeginTime()))
                            .setEndTime(DateKit.toDate(qualificationParam.getEndTime()))
                            .save();
                }
            }

        // 保存其他
        if (otherParams != null)
            for (OtherParam otherParam : otherParams) {
                AuditConfig auditConfig = AuditConfig.dao.findById(otherParam.getId());
                for (String file : otherParam.getFiles()) {
                    CompanyInfo companyInfo = new CompanyInfo();
                    companyInfo.setValue(otherParam.getValue())
                            .setAccessory(file)
                            .setCompanyId(companyId)
                            .setConfigId(otherParam.getId())
                            .setRequire(auditConfig.getRequire())
                            .save();
                }
            }
        renderJson(ResultKit.success(this));

    }

    /**
     * 审核
     *
     * @param id|企业id|Integer|必填
     * @param allow|是否通过1-通过0-不通过|Integer|必填
     * @param images|图片|String|否
     * @param reason|原因|String|否
     * @title 审核
     */
    @RequiresPermissions("platform:update")
    @Before(Tx.class)
    public void edit() {
        Company company = getModel(Company.class, "");
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        Company old = Company.dao.findById(company.getId());
        old.setAllow(company.getAllow())
                .setImages(company.getImages())
                .setReason(company.getReason())
                .setAuditTime(new Date())
                .setAuditUser(user.getId())
                .setStatus(2)
                .update();
        user = User.dao.findById(old.getUserId());
        user.use(Constant.PLATFORM_MODULE).setStatus(1).update();

        renderJson(ResultKit.success(this));
    }

    /**
     * 查看企业账号
     *
     * @param id|企业id|Integer|必填
     * @title 查看企业账号
     */
    @Before(RequiredIdValidator.class)
    @RequiresPermissions("platform:read")
    public void userInfo() {
        Integer id = getParaToInt("id");
        Company company = Company.dao.findById(id);
        User user = User.dao.findById(company.getUserId());
        JMap jMap = JMap.create();
        jMap.set("user_code", user.getUserCode())
                .set("company_name", company.getName());
        renderJson(ResultKit.success(jMap));
    }

    /**
     * 修改企业密码
     *
     * @param id|企业id|Integer|必填
     * @param password|密码|String|必填
     * @param rePassword|确认密码|String|必填
     * @title 修改企业密码
     */
    @Before({ RequiredIdValidator.class, Tx.class })
    @TxConfig(Constant.PLATFORM_MODULE)
    @RequiresPermissions("platform:update")
    public void editPassword() {
        String password = getPara("password");
        String rePassword = getPara("rePassword");
        // 如果密码为空或者不一致
        if (StrKit.isBlank(rePassword) || !rePassword.equals(password)) {
            renderJson(ResultKit.fail(I18nKit.get("password_different", Constant.COMMON_MODULE, this)));
            return;
        }
        Integer id = getParaToInt("id");

        // 获取企业信息和用户信息并修改
        Company company = Company.dao.findById(id);
        User user = User.dao.findById(company.getUserId());
        User opUser = (User) SecurityUtils.getSubject().getPrincipal();
        company.setEditTime(new Date())
                .setEditUser(opUser.getId())
                .update();
        user.setPassword(PasswordKit.passwordService.encryptPassword(password))
                .update();

        renderJson(ResultKit.success(this));
    }
}
